<!-- src/views/Coach/CoachAppointment.vue -->
<template>
  <div class="coach-appointment">
    <el-card class="main-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">我的预约</span>
          <div class="header-controls">
            <el-input
              v-model="searchQuery"
              placeholder="请输入学员姓名"
              style="width: 220px; margin-right: 15px;"
              clearable
              @input="debouncedSearch"
              @clear="fetchAppointments"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select
              v-model="statusFilter"
              placeholder="请选择状态"
              style="width: 130px; margin-right: 15px;"
              @change="handleStatusFilterChange"
            >
              <el-option label="全部" value=""></el-option>
              <el-option label="待确认" value="PENDING"></el-option>
              <el-option label="已确认" value="CONFIRMED"></el-option>
            </el-select>
          </div>
        </div>
      </template>

      <!-- 预约表格 -->
      <el-table
        :data="filteredAppointments"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        border
      >
        <el-table-column label="序号" width="60" align="center">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="student.fullname" label="学员姓名" min-width="100" />
        <el-table-column prop="program.name" label="科目名称" min-width="120" />
        <el-table-column prop="appointment_date" label="预约日期" min-width="110" />
        <el-table-column prop="start_time" label="开始时间" min-width="100" />
        <el-table-column prop="end_time" label="结束时间" min-width="100" />
        <el-table-column prop="status_text" label="状态" min-width="90">
          <template #default="scope">
            <el-tag
              :type="scope.row.status === 'PENDING' ? 'warning' :
                     scope.row.status === 'CONFIRMED' ? 'success' : 'info'">
              {{ scope.row.status_text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right" align="center">
          <template #default="scope">
            <div class="operation-cell">
              <div v-if="scope.row.status === 'PENDING'">
                <el-button size="small" type="success" @click="confirmAppointment(scope.row)">通过</el-button>
                <el-button size="small" type="warning" @click="cancelAppointment(scope.row)">取消</el-button>
              </div>
              <div v-else-if="scope.row.status === 'CONFIRMED'">
                <el-button size="small" type="warning" @click="cancelAppointment(scope.row)">取消</el-button>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          background
        />
      </div>
    </el-card>

    <!-- 预约详情对话框 -->
    <el-dialog v-model="dialogVisible" title="预约详情" width="500" center>
      <el-form :model="currentAppointment" label-width="100px" label-position="left">
        <el-form-item label="预约日期:">
          <el-input v-model="currentAppointment.appointment_date" readonly />
        </el-form-item>
        <el-form-item label="预约时间:">
          <el-input :value="formatTimeRange(currentAppointment.start_time, currentAppointment.end_time)" readonly />
        </el-form-item>
        <el-form-item label="学员姓名:">
          <el-input :value="currentAppointment.student?.fullname" readonly />
        </el-form-item>
        <el-form-item label="训练项目:">
          <el-input :value="currentAppointment.program?.name" readonly />
        </el-form-item>
        <el-form-item label="预约状态:">
          <el-tag :type="getStatusType(currentAppointment.status_text)" size="small">
            {{ currentAppointment.status_text }}
          </el-tag>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import requestUtil from '@/util/request.js'
import debounce from 'lodash/debounce'

// 数据相关
const appointments = ref([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const statusFilter = ref('') // 状态筛选条件
const loading = ref(false)
const dialogVisible = ref(false)
const currentAppointment = ref({})

// 获取教练的所有预约
const fetchAppointments = async () => {
  loading.value = true
  try {
    const userId = localStorage.getItem('user_id')
    if (!userId) {
      ElMessage.error('用户未登录或会话已过期')
      return
    }

    // 使用新的接口，专门针对教练查询预约
    const response = await requestUtil.get(`/appointment/msg/coach/${userId}`, {
      params: {
        page: currentPage.value,
        page_size: pageSize.value
      }
    })

    console.log('原始响应数据:', response.data);

    if (response.data?.status === 200) {
      // 根据状态筛选条件过滤数据
      let filteredData = response.data.data?.list || []

      // 如果选择了状态筛选条件，则进行筛选
      if (statusFilter.value) {
        filteredData = filteredData.filter(app => app.status === statusFilter.value)
      } else {
        // 如果没有选择筛选条件，默认只显示待确认和已确认的预约
        filteredData = filteredData.filter(app =>
          app.status === 'PENDING' || app.status === 'CONFIRMED'
        )
      }

      appointments.value = filteredData.map(item => {
        // console.log('处理单个预约项:', item);

        return {
          ...item,
          // 从嵌套对象中提取ID字段
          student_id: item.student?.id,
          coach_id: item.coach?.id,
          program_id: item.program?.id,
          start_time: formatTime(item.start_time),
          end_time: formatTime(item.end_time),
          status_text: getStatusText(item.status)
        }
      })

      total.value = response.data.data?.total || filteredData.length
    }
  } catch (error) {
    console.error('获取预约信息失败:', error)
    ElMessage.error('获取预约信息失败: ' + (error.message || '未知错误'))
    appointments.value = []
  } finally {
    loading.value = false
  }
}

// 搜索相关
const filteredAppointments = computed(() => {
  if (!searchQuery.value.trim()) return appointments.value
  return appointments.value.filter(app =>
    app.student?.fullname?.includes(searchQuery.value)
  )
})

const debouncedSearch = debounce(fetchAppointments, 300)

// 分页相关
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchAppointments()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchAppointments()
}

// 状态筛选变化处理
const handleStatusFilterChange = () => {
  currentPage.value = 1 // 重置到第一页
  fetchAppointments()
}

// 确认预约并创建或更新训练记录
const confirmAppointment = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要确认这个预约吗？`,
      '确认预约',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 更新预约状态为CONFIRMED
    const res = await requestUtil.put(`/appointment/update/${row.appointment_id}`, {
      ...row,
      status: 'CONFIRMED'
    });

    if (res.data?.status === 200) {
      // 如果原状态是PENDING，则创建或更新训练记录
      if (row.status === 'PENDING') {
        try {
          // 获取教练信息
          const userId = localStorage.getItem('user_id');
          const coachRes = await requestUtil.get(`/coach/msg/userId/${userId}`);
          const coachName = coachRes.data.data?.fullname || '未知';

          // 从嵌套对象中获取ID
          const studentId = row.student?.id;
          const coachId = row.coach?.id;
          const programId = row.program?.id;
          // console.log('从嵌套对象中获取的ID:', studentId, coachId, programId)

          // 检查必要字段是否存在
          if (!studentId || !coachId || !programId) {
            ElMessage.error('预约数据不完整，缺少必要的ID字段');
            return;
          }

          // 先检查学生是否已有该项目的训练记录
          const existingTrainingRes = await requestUtil.get('/student_training/trainings', {
              student_id: studentId,
              program_id: programId

          });
          // console.log('检查学生是否已有该项目的训练记录的响应数据:', existingTrainingRes.data)

          let trainingResult;

          if (existingTrainingRes.data?.status === 200 && existingTrainingRes.data.data?.length > 0) {
            // 如果存在现有记录，则更新第一条记录
            const existingTraining = existingTrainingRes.data.data[0];
            // console.log('已有的训练记录:', existingTraining)

            // 使用正确的PUT路径更新训练记录
            trainingResult = await requestUtil.put(`/student_training/trainings/update/${existingTraining.training_id}`, {
              coach_id: coachId,
              start_time: `${row.appointment_date} ${row.start_time}:00`,
              end_time: `${row.appointment_date} ${row.end_time}:00`,
              status: 'SCHEDULED',
              rating: 1,
              feedback: '',
              content: `${coachName}通过`
            });

            if (trainingResult.data?.status === 200) {
              ElMessage.success('预约已确认，现有训练记录已更新');
            } else {
              ElMessage.warning('预约已确认，但训练记录更新失败: ' + (trainingResult.data?.message || '未知错误'));
            }
          } else {
            // 如果不存在现有记录，则创建新记录
            trainingResult = await requestUtil.post('/student_training/trainings/add', {
              student_id: studentId,
              coach_id: coachId,
              program_id: programId,
              start_time: `${row.appointment_date} ${row.start_time}:00`,
              end_time: `${row.appointment_date} ${row.end_time}:00`,
              status: 'SCHEDULED',
              rating: 1,
              feedback: '',
              content: `${coachName}通过`
            });

            if (trainingResult.data?.status === 201) {
              ElMessage.success('预约已确认，训练记录已创建');
            } else {
              ElMessage.warning('预约已确认，但训练记录创建失败: ' + (trainingResult.data?.message || '未知错误'));
            }
          }
        } catch (trainingError) {
          console.error('训练记录操作失败:', trainingError);
          ElMessage.warning('预约已确认，但训练记录操作失败: ' + (trainingError.response?.data?.message || trainingError.message));
        }
      } else {
        ElMessage.success('预约已确认');
      }

      await fetchAppointments();
    } else {
      ElMessage.error(res.data?.message || '确认失败');
    }
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消操作');
      return;
    }
    ElMessage.error(error.response?.data?.message || '确认失败');
  }
}

// 取消预约
const cancelAppointment = async (row) => {
  try {
    await ElMessageBox.confirm(
        '确定要取消这个预约吗？',
        '取消预约',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )

    const res = await requestUtil.put(`/appointment/update/${row.appointment_id}`, {
      ...row,
      status: 'CANCELLED'
    })

    if (res.data?.status === 200) {
      ElMessage.success('预约已取消')
      await fetchAppointments()
    } else {
      ElMessage.error(res.data?.message || '取消失败')
    }
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消操作')
      return
    }
    ElMessage.error(error.response?.data?.message || '取消失败')
  }
}

// 工具函数：格式化时间
const formatTime = (timeString) => {
  try {
    if (!timeString || typeof timeString !== 'string') {
      return '--:--'
    }
    const parts = timeString.split(':')
    if (parts.length >= 2) {
      return `${parts[0]}:${parts[1]}`
    }
    return '--:--'
  } catch (error) {
    console.error('格式化时间出错:', error)
    return '--:--'
  }
}

// 工具函数：格式化时间范围
const formatTimeRange = (startTime, endTime) => {
  try {
    return `${formatTime(startTime)}-${formatTime(endTime)}`
  } catch (error) {
    console.error('格式化时间范围出错:', error)
    return '--:--'
  }
}

// 工具函数：获取状态文本
const getStatusText = (status) => {
  try {
    const statusValue = status?.toUpperCase()
    switch (statusValue) {
      case 'CONFIRMED':
        return '已确认'
      case 'PENDING':
        return '待确认'
      case 'COMPLETED':
        return '已完成'
      case 'CANCELLED':
        return '已取消'
      default:
        return status || '未知状态'
    }
  } catch (error) {
    console.error('获取状态文本出错:', error, {status})
    return '未知状态'
  }
}

// 工具函数：获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '已确认':
      return 'success'
    case '待确认':
      return 'warning'
    case '已完成':
      return 'primary'
    case '已取消':
      return 'danger'
    default:
      return 'info'
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAppointments()
})
</script>

<style scoped>
.coach-appointment {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 84px);
}

.main-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  align-items: center;
}

.operation-cell {
  display: flex;
  gap: 5px;
  justify-content: center;
}

.operation-cell .el-button {
  margin-right: 5px;
}

.operation-cell .el-button:last-child {
  margin-right: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-table th) {
  font-weight: 600;
}

:deep(.el-table .el-table__cell) {
  padding: 8px 0;
}
</style>
